import COS from 'cos-nodejs-sdk-v5'

const cos = new COS({
    SecretId: 'AKID67ykKnAT9kEbuDUefUOBmFdu47BA5zlP', // 推荐使用环境变量获取；用户的 SecretId，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参考https://cloud.tencent.com/document/product/598/37140
    SecretKey: 'e8QdiHr9MUWYl3V9nldewHmOB84rlqvy', // 推荐使用环境变量获取；用户的 SecretKey，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参考https://cloud.tencent.com/document/product/598/37140
});

const Bucket = 'roxy2-1323584518'
const Region = 'ap-beijing'

/*
    Key: 上传后的文件名

    FilePath: 文件在本机的路径
 */

export const upload = async (Key: string, FilePath: string) => {
    return await cos.uploadFile({
        Bucket,
        Region,
        Key,
        FilePath,
        onProgress: function (progressData) {
            console.log(JSON.stringify(progressData));
        }
    })
}
/*
    获取存储桶内所有对象
 */
export const getBucket = async () => {
    return await cos.getBucket({
        Bucket,
        Region,
    })
}

const getPromiseObjectUrl = async (options: Object) => {
    return new Promise((resolve, reject) => {
        cos.getObjectUrl(<COS.GetObjectUrlParams>options, (err, data) => {
            if (err) {
                reject(err);
            } else {
                // console.log(data.Url)
                resolve(data.Url);
            }
        })
    })
}

/*
    通过对象名返回暂时可访问的url,

    Key: 文件名/对象名
 */
export const getUrl = async (Key: string, Expired = 600) => {
    try {
        return await getPromiseObjectUrl({
            Key,
            Bucket,
            Region,
            Expired
        });
    } catch (error) {
        console.error(error);
        throw error;
    }
};

// SecretId:AKID67ykKnAT9kEbuDUefUOBmFdu47BA5zlP
// SecretKey:e8QdiHr9MUWYl3V9nldewHmOB84rlqvy